<!-- 发布页 -->
<template>
  <div id="postpage">
    <div class="postpage-container" :class="{ sendpost: sending }">

      <!-- 头图区 -->
      <div class="header-picture" :class="[headpic?'':'header-pic-bg']">
        <div class="header-picture-preview">
          <img
            :src="headpic"
            v-if="headpic"
            class="header-picture-preview-inner"
          />
          <div class="header-picture-op-wrap" v-if="headpic">
            <button @click="changeImg">
              <svg class="icon" aria-hidden="true">
                <use xlink:href="#icon-cmgaishan"></use>
              </svg>
            </button>
            <button @click="clearImg">
              <svg class="icon" aria-hidden="true">
                <use xlink:href="#icon-cmshanchu"></use>
              </svg>
            </button>
          </div>
        </div>
        <input
          type="file"
          accept=".jpeg, .jpg, .png"
          class="upload-header-picture"
          ref="picuploader"
          @change="handlePic"
        />
        <svg
          class="icon upload-header-picture-icon"
          aria-hidden="true"
          v-if="!headpic"
        >
          <use xlink:href="#icon-cmchangyongicon-"></use>
        </svg>
      </div>
      <!-- 头图区 -->

      <!-- 标题 -->
      <textarea
        class="input-title"
        placeholder="在此处键入标题"
        v-model="post_title"
      ></textarea>
      <!-- 标题 -->

      <!-- 正文区 -->
      <p class="content-tip">在下方区域编辑正文</p>
      <div class="edit-area">
        <posteditor
          ref="posteditor"
          v-model="editorvalue"
          :value="editorvalue"
        ></posteditor>
      </div>
      <!-- 正文区 -->
    </div>

    <!-- 右侧操作区 -->
    <div class="post-operation">
      <p v-show="!edit">选择发布社区</p>
      <cm-selector
        :value="dSelection"
        v-model="selection"
        :defaultSelection="selection"
        v-show="!edit"
      >
        <cm-selector-option
          v-for="community in subCommunities"
          :key="community.communityNo"
          :value="community.communityNo"
          >{{ community.communityName }}</cm-selector-option
        >
      </cm-selector>

      <!-- 标签选择区 -->
      <div class="add-tags">
        <p>选择标签</p>
        <div @keydown.esc="addTag">
          <tag
            v-for="(tag, index) in tagsChosen"
            :key="tag + index"
            :closable="true"
            @close="handleClose(tag)"
            >{{ tag.labelName }}</tag
          >
          <tag @handleChange="addTag" v-if="!addingTag">+</tag>
          <CmInputMini
            :placeholder="'创建标签'"
            @submit="submit"
            v-if="addingTag"
            :wordsLimit="15"
          >
          </CmInputMini>
        </div>
        <div>
          <tag
            v-for="(tag, index) in hotTags"
            :key="tag + index"
            @handleChange="handleChange(tag)"
            v-model="tag.checked"
            :closable="false"
            >{{ tag.labelName }}</tag
          >
          <tag @handleChange="randTags">换一换</tag>
        </div>
      </div>
      <!-- 标签选择区 -->

      <button class="post-confirm-button" @click="completePost()">
        <svg class="icon" aria-hidden="true">
          <use xlink:href="#icon-cmfabu"></use>
        </svg>
        发布
      </button>
    </div>
    <!-- 右侧操作区 -->
  </div>
</template>

<script>
import CmSelectorOption from "../components/common/selector/cm-selector-option.vue";
import CmSelector from "../components/common/selector/cm-selector.vue";
import posteditor from "../components/editor/posteditor.vue";
import { readImg, compressImg } from "../utils/utils";
import { mapGetters } from "vuex";
import { getHeadPicUrl, addTagsStatus } from "../utils/utils";
import baseurl from "../requestsetting/services/baseurl";
import Tag from "../components/common/tag/tag.vue";
import CmInputMini from "../components/common/input/cm-input-mini.vue";

export default {
  data() {
    return {
      selection: 0, //选中项目主键
      headpic: "",
      editorvalue: "", //正文输入区数据
      post_title: "",
      sending: false,
      edit: false,
      hotTags: [], //热门标签
      tagsChosen: [], //保存选中标签
      addingTag: false, //是否为添加标签状态
      oldTags: [], //编辑帖子时暂存老标签,checked为true即选中状态不发回后端处理，为false即未选中状态发回后端处理
      oldTagsCanceled: [], //取消掉的老标签
    };
  },

  components: {
    posteditor,
    CmSelector,
    CmSelectorOption,
    Tag,
    CmInputMini,
  },

  computed: {
    dSelection: function () {
      let communityName = "";
      this.subCommunities.forEach((element) => {
        if (element.communityNo == this.selection)
          communityName = element.communityName;
      });
      return communityName;
    }, //选中项目的标题（值）用以直观展示
    ...mapGetters([
      "user",
      "subCommunities", //用户关注社区，包含部分热门社区
      "postContent",
    ]),
  },

  methods: {
    editorValueChange(val) {
      this.editorvalue = val; //正文输入区数据
    },
    async handlePic(e) {
      //上传头图
      const that = this;
      var file = e.target.files[0];
      console.log(file);
      if (file != undefined) {
        const img = await readImg(file);
        const blob = await compressImg(img, file.type, 1000, 1000);
        let param = new FormData();
        param.append("file", blob, "file.jpg");
        console.log(param.get("file"));
        let config = {
          //用form表单形势上传文件
          headers: {
            "Content-Type": "multipart/form-data",
          },
          transformRequest: [
            function (data) {
              return data;
            },
          ],
        };
        this.$getApi.uploadPostPicture(param, config).then((res) => {
          //上传头图并从服务器获得图片地址渲染
          console.log(res);
          that.headpic = baseurl + res.data.file;
        });
      }
    },
    changeImg() {
      this.$refs.picuploader.dispatchEvent(new MouseEvent("click")); //更换头图
    },
    clearImg() {
      //删除头图
      const that = this;
      const pic = this.headpic.split("image/")[1];
      this.$getApi.deletePostPhoto(pic).then((res) => {
        console.log(res);
        that.headpic = "";
      });
    },
    completePost() {
      //上传帖子
      const that = this;
      let headpicture = this.headpic + "<headpicsplit>"; //为头图添加特殊标签

      // 帖子内容
      let post = new Object();
      post.postTitle = this.post_title;
      post.userNo = this.user.userNo;
      post.communityNo = this.selection;
      let newdate = new Date();
      post.postTime = newdate.toLocaleString("chinese", { hour12: false });
      post.postTime = post.postTime.replace(/\//g, "-");
      console.log(post.postTime);
      post.endingTime = post.postTime;
      post.postContent = headpicture + this.editorvalue;
      console.log(post);
      // 帖子内容

      let op = this.$route.query.operation;
      if (this.selection != 0) {
        if (op == "editpost") {
          //编辑帖子
          // eslint-disable-next-line no-unused-vars
          this.$getApi.editTopic(post, this.postContent.postNo).then((res) => {
            console.log("edittopic");
            that.sending = true;
            that.postTags(this.postContent.postNo);
            setTimeout(function () {
              that.$router.push({
                path: "/browsetopic",
                query: { postNo: that.postContent.postNo },
              });
            }, 400);
          });
        } else {
          //新增
          this.$getApi.postTopic(post).then((res) => {
            console.log(res);
            that.sending = true;
            that.postTags(res.data.postNo);
            setTimeout(function () {
              that.$router.push({
                path: "/browsetopic",
                query: { postNo: res.data.postNo },
              });
            }, 400);
          });
        }
      } else {
        alert("请选择发布社区");
      }
    },

    getSubCommunities() {},

    tagCompare(tag, list) {
      //判断一个列表中是否包含某标签
      console.log("begin--tagCompare:", tag, list);
      for (let i = 0; i < list.length; i++) {
        if (tag.labelNo == list[i].labelNo) {
          console.log("tagCompare", true);
          return true;
        }
      }
      console.log("tagCompare", false);
      return false;
    },

    handleChange(tag) {
      //标签点击事件
      if (tag.checked == false) {
        console.log('选中标签')
        if (this.tagsChosen.length == 6) alert("最多选择6个标签");
        else {
          this.tagsChosen = [...this.tagsChosen, tag];
          tag.checked = true;
          for(let i=0;i<this.oldTagsCanceled.length;i++){
            if(tag.labelNo == this.oldTagsCanceled[i].labelNo){
              this.oldTagsCanceled.splice(i,1);
              console.log('删除oldtagcanceled项目')
              break;
            }
          }
        }
      } else {
        tag.checked = false;
        let deleteIndex;
        for (let i = 0; i < this.tagsChosen.length; i++) {
          if (this.tagsChosen[i].labelNo == tag.labelNo) deleteIndex = i;
        }

        if (
          this.tagCompare(this.tagsChosen[deleteIndex],this.oldTags) == true
        ) {
          this.oldTagsCanceled.push(this.tagsChosen[deleteIndex]);
        }
        this.tagsChosen.splice(deleteIndex, 1);
      }
    },
    handleClose(tag) {
      //标签关闭事件
      let deleteIndex = this.tagsChosen.indexOf(tag);
      let disableIndex = this.hotTags.indexOf(tag);
      this.tagsChosen.splice(deleteIndex, 1);
      for (let i = 0; i < this.hotTags.length; i++) {
        if (this.hotTags[i].labelNo == tag.labelNo) disableIndex = i;
      }
      // if (this.tagCompare(this.hotTags[disableIndex],this.oldTags) == true) {
      //   this.oldTagsCanceled.push(this.hotTags[disableIndex]);
      // }
      if (this.tagCompare(tag,this.oldTags) == true) {
        this.oldTagsCanceled.push(tag);
      }
      if (disableIndex != -1) this.hotTags[disableIndex].checked = false;
    },

    addTag() {
      //添加标签
      this.addingTag = !this.addingTag;
    },
    submit(value) {
      //提交标签
      if (this.tagsChosen.length < 6) {
        let tag = {
          labelName: value,
          checked: false,
        };
        console.log("创建标签", tag);
        this.addTag();
        const that = this;
        this.$getApi.addTag(value).then((res) => {
          if(that.tagCompare(res.data.label1,that.tagsChosen)==false)
          {
            for(let i=0;i<that.hotTags.length;i++){
              if(that.hotTags[i].labelNo == res.data.label1.labelNo){
                that.hotTags[i].checked = true
              }
            }
            that.tagsChosen = [...that.tagsChosen, res.data.label1];
          }
        });
      } else {
        alert("最多6个标签");
      }
    },
    randTags() {
      //获取随机标签列表
      const that = this;
      this.$getApi.getRandomTags().then((res) => {
        that.hotTags = addTagsStatus(res.data.labels.splice(0, 9),false);
        let tagschosen = that.tagsChosen;
        console.log("tagschosen", that.tagsChosen);
        that.hotTags.forEach((tag) => {
          tagschosen.forEach((chosedtag) => {
            if (tag.labelNo == chosedtag.labelNo) {
              console.log("对比tag相等");
              tag.checked = true;
            }
          });
        });
      });
    },
    postTags(postNo) {
      //为帖子添加标签
      let config = {
        headers: {
          "Content-Type": "application/json",
        },
        transformRequest: [
          function (data) {
            return JSON.stringify(data);
          },
        ],
      };
      console.log("帖子打标签");
      let tags = [];
      let tagsTemp = []
      let deleteIndex;
      let i = 0
      while ( i < this.tagsChosen.length) {
        console.log(i)
        // for (let j = 0; j < this.oldTags.length; j++) {
          if(this.tagCompare(this.tagsChosen[i],this.oldTags) == true)
          // if (this.tagsChosen[i].labelNo == this.oldTags[j].labelNo) {
            {deleteIndex = i;
            this.tagsChosen.splice(deleteIndex, 1);
            i = 0;
            }
            else{
              i++;
            }
          // }
        // }
      }
      tagsTemp.push.apply(tagsTemp, this.oldTagsCanceled);
      tagsTemp.push.apply(tagsTemp,this.tagsChosen)
      console.log("最终列表",tagsTemp)

      for (let i = 0; i < tagsTemp.length; i++) {
        console.log(tagsTemp[i]);
        let tag = {};
        tag.obNo = postNo;
        tag.labelNo = tagsTemp[i].labelNo;
        tag.obType = 1;
        tags.push(tag);
      }


      console.log(JSON.stringify(tags));
      this.$getApi.giveAndRemoveTags(tags, config);
    },
  },
  created() {
    let op = this.$route.query.operation;
    if (this.postContent && op == "editpost") {
      this.headpic = getHeadPicUrl(this.postContent.postContent);
      this.editorvalue =
        this.postContent.postContent.split("<headpicsplit>")[1];
      this.post_title = this.postContent.postTitle;
      this.selection = this.postContent.communityNo;
      this.edit = true;
      const that = this;
      this.$getApi.findRelatedTags(this.postContent.postNo, 1).then((res) => {
        that.tagsChosen = addTagsStatus(res.data.labels,true);
        that.randTags();
        // that.oldTags = that.tagsChosen;
        that.oldTags.push.apply(that.oldTags,that.tagsChosen)
      });
    } else {
      this.randTags();
    }
  },
  watch: {
    editorvalue(newval) {
      console.log("editorvaluechange", newval); //帖子正文实时更新，由posteditor传回
    },
    post_title(newval) {
      console.log("title", newval);
    },
    oldTagsCanceled(newval){
      console.log('oldtagcanceled',newval)
    },
    oldTags(newval){
      console.log('oldtags',newval)
    },
    tagsChosen(newval){
      console.log('tagsChosen',newval)
    }
  },
};
</script>
<style>
/* #postpage{
    position: fixed;
    width: 100%;
    height: 100%;
    top: 0;
    left: 0;
    z-index: 2;
} */
.postpage-container {
  position: relative;
  top: 8rem;
  width: 40%;
  height: 960px;
  display: flex;
  align-content: flex-start;
  justify-content: center;
  flex-wrap: wrap;
  overflow-y: scroll;
  margin: 0 auto;
  z-index: 10;
}
.header-picture {
  position: relative;
  width: 100%;
  min-height: 190px;
  z-index: 20;
  display: block;
}
.header-pic-bg{
  background-color: rgba(238, 248, 255, 0.891);
}
.header-picture-preview {
  position: relative;
  width: 100%;
  margin: 0;
  margin-bottom: -5px;
}
.header-picture-preview img.header-picture-preview-inner {
  position: relative;
  width: 100%;
  z-index: 21;
  margin: 0;
  padding: 0;
}

/* 对图片操作 */
.header-picture-op-wrap {
  position: absolute;
  width: 60px;
  height: 30px;
  right: 0;
  bottom: 4px;
  z-index: 21;
  background-color: rgba(0, 0, 0, 0.156);
  backdrop-filter: blur(10px);
  margin: 0;
  padding: 0;
}
.header-picture-op-wrap button {
  border: none;
  outline: none;
  float: right;
  height: 30px;
  width: 30px;
  background-color: transparent;
  margin: 0;
  padding: 0;
  font-size: 15px;
  color: rgba(255, 255, 255, 0.925);
}
/* 对图片操作 */

/* 上传图片input */
input.upload-header-picture {
  position: absolute;
  top: 0;
  left: 0;
  display: block;
  height: 190px;
  width: inherit;
  opacity: 0;
}
/* 上传图片input */

.header-pic-bg:hover:after {
  position: absolute;
  content: "添加主题图片";
  left: 0;
  font-size: 14px;
  color: rgb(69, 73, 78);
  height: 16px;
  text-align: center;
  width: 100%;
  line-height: 16px;
  bottom: 50px;
  transition: all 0.3s ease;
  animation: showup 0.3s ease;
  z-index: 20;
}
@keyframes showup {
  0% {
    transform: scaleY(0);
    transform-origin: top;
  }
  100% {
    transform: scaleY(1);
    transform-origin: top;
  }
}
.upload-header-picture-icon {
  color: rgb(215, 225, 238);
  font-size: 40px;
  position: absolute;
  background: inherit;
  top: 50%;
  left: 50%;
  transform: translateX(-50%) translateY(-50%);
}
.postpage-container > .input-title {
  margin-top: 1rem;
  padding: 5px 0;
  outline: none;
  border: none;
  border-radius: 4px;
  width: 100%;
  height: 50px;
  font-size: 32px;
  font-weight: 600;
  line-height: 50px;
  color: rgb(71, 71, 71);
  resize: none;
  overflow: auto;
}
.postpage-container > .content-tip {
  width: 100%;
  font-size: 20px;
  color: rgb(133, 144, 166);
  height: 40px;
  line-height: 40px;
  border-top: 1px rgb(133, 144, 166) solid;
  border-bottom: 1px rgb(133, 144, 166) solid;
  background-color: rgba(255, 255, 255, 0.898);
  margin: 20px 0 0 0;
  position: sticky;
  top: 0;
  z-index: 20;
}
.edit-area {
  position: relative;
  width: 100%;
  min-height: 960px;
  border: none;
  line-height: 1.6;
  border-radius: 4px;
}
.edit-area > div .edit-area > input {
  border: none;
  background-color: rgb(255, 253, 250);
}

/* 右侧操作区 */
.post-operation {
  width: 200px;
  position: absolute;
  left: 70%;
  margin-left: 60px;
  top: 8rem;
  bottom: 4rem;
  padding: 5px 10px;
}
.post-operation p {
  border-left: 5px blue solid;
  padding: 0 10px;
  font-size: 14px;
  color: rgb(56, 56, 56);
}

/* 标签选择区域 */
.add-tags {
  margin-top: 50px;
  max-height: 70%;
  width: 100%;
  transition: all 0.2s;
  overflow-y: scroll;
}
.add-tags > div:nth-child(2) {
  width: calc(100% - 10px);
  min-height: 20px;
  padding: 5px 5px;
  border-bottom: 1px rgb(209, 209, 209) solid;
}
.add-tags > div:nth-child(3) {
  margin-top: 10px;
  width: calc(100% - 10px);
  padding: 5px 5px;
}

/* 发布按钮 */
button.post-confirm-button {
  border: none;
  outline: none;
  position: absolute;
  bottom: 0;
  height: 30px;
  width: 60px;
  left: 75px;
  color: white;
  background-color: rgba(0, 145, 255, 0.476);
  border-radius: 2px;
  transition: all 0.2s;
}
button.post-confirm-button > .icon {
  font-size: 14px;
}
button.post-confirm-button:hover {
  background-color: rgb(0, 145, 255);
}
.sendpost {
  box-shadow: 0 5px 15px -5px rgba(0, 0, 0, 0.5);
  animation: sending 0.4s ease;
}
@keyframes sending {
  to {
    top: -20rem;
    opacity: 0;
    transform: scale(0);
  }
}
</style>